package com.byb.server.service.impl;

import com.byb.server.service.UtilService;
import com.byb.server.service.dto.Wc.WCAppInfoDTO;
import com.byb.server.service.dto.WordKeyDTO;
import com.google.gson.Gson;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.security.DigestException;
import java.util.*;

import static com.byb.server.service.util.WcUtil.Wc_SHA1.SHA1;

@Service
public class UtilServiceImpl implements UtilService{

    private final Logger log = LoggerFactory.getLogger(UtilService.class);

    private final Gson gson = new Gson();

    private final String appid = "wxb2b467961e051c00";

    @Override
    public String postWeiXinCode(String url) {
        OkHttpClient client = new OkHttpClient();
        log.debug("Request to WeChat access_token : {}",url);
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Code"+response);
                }
                Headers responseHeaders = response.headers();
                for (int i = 0; i < responseHeaders.size(); i++) {
                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }
                WordKeyDTO wordKeyDTO =  gson.fromJson(response.body().charStream(), WordKeyDTO.class);
                System.out.println(response.body().string());

            }

        });
        return null;
    }

    /**
     *  获取access_token
     * @param url
     * @return
     */
    @Override
    public WCAppInfoDTO getWc_config(String url) {
        WCAppInfoDTO wcAppInfoDTO=new WCAppInfoDTO();
        Map<String,String> maps = new HashMap<String,String>();
        maps.put("jsapi_ticket",WcAccessTokenTask.jsapi_ticket_vm.getTicket());
        maps.put("noncestr", String.valueOf(UUID.randomUUID()));
        maps.put("timestamp", String.valueOf(System.currentTimeMillis()));
        maps.put("url",url );
        try {
            wcAppInfoDTO.setSignature(SHA1(maps));
        } catch (DigestException e) {
            e.printStackTrace();
        }

        wcAppInfoDTO.setTimestamp(maps.get("timestamp"));
        wcAppInfoDTO.setNonceStr(maps.get("noncestr"));
        wcAppInfoDTO.setAppId(appid);

        return wcAppInfoDTO;
    }







}
